package com.yusvn.scm.admin.service;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.yusvn.scm.common.BaseService;
import com.yusvn.scm.common.kit.RetKit;
import com.yusvn.scm.common.model.SysMenu;
import com.yusvn.scm.common.model.SysRole;
import com.yusvn.scm.common.model.SysRoleMenu;

/**
 * 角色管理
 * @author liugz
 *
 */
public class AdminRoleService extends BaseService{

	private SysRole dao = new SysRole().dao();
	private SysMenu menuDao = new SysMenu().dao();
	private SysRoleMenu roleMenuDao = new SysRoleMenu().dao();
	
	/**
	 * 获取用户角色
	 * @param userId
	 * @return
	 */
	public List<SysRole> getUserRole(Integer userId) {
		List<SysRole> list = dao.find("SELECT * FROM sys_role "
				+ "WHERE role_id IN (SELECT role_id FROM sys_user_role WHERE user_id=? )", userId);
		return list;
	}
	
	public Page<SysRole> page(Kv kv) {
		Page<SysRole> list = dao.template("admin.role.page", kv).paginate(getPage(kv), getLimit(kv));
		return list;
	}

	public SysRole get(Object idValue) {
		return dao.findById(idValue);
	}

	public List<SysRole> list() {
		return dao.findAll();
	}
	
	public boolean exists(int roleId, String name, String code) {
		name = name.toLowerCase().trim();
		String sql = "select role_id from sys_role where (role_name = ? or role_code=?) and role_id != ? limit 1";
		Integer id = Db.queryInt(sql, name, code, roleId);
		return id != null;
	}
	
	public RetKit save(String jsonObj) {
		SysRole role = JSON.parseObject(jsonObj, SysRole.class);
		
		if (exists(-1, role.getRoleName(), role.getRoleCode() )) {
			return RetKit.fail("名称或标识已经存在，请输入别的名称");
		}
		
		role.setRoleName(role.getRoleName().trim());
		
		if(role.save()) {
			return RetKit.ok("添加成功");
		}
		
		return RetKit.fail("添加失败");
	}

	public RetKit update(String jsonObj) {
		SysRole role = JSON.parseObject(jsonObj, SysRole.class);
		
		if (exists(role.getRoleId(), role.getRoleName(), role.getRoleCode() )) {
			return RetKit.fail("名称或标识已经存在，请输入别的名称");
		}
		
		role.setRoleName(role.getRoleName().trim());
		
		if(role.update()) {
			return RetKit.ok("修改成功");
		}
		
		return RetKit.fail("修改失败");
	}

	public RetKit remove(String id) {
		if(dao.deleteById(id)) {
			return RetKit.ok("删除成功");
		}
		return RetKit.fail("删除失败");
	}

	public RetKit removeBatch(String idsStr) {
		JSONObject idsObj = JSON.parseObject(idsStr);
		JSONArray idsArr = idsObj.getJSONArray("ids");
		
		Object[][] paras = new Object[idsArr.size()][1];
		for(int i=0;i<idsArr.size();i++) {
			paras[i][0] = idsArr.get(i);
		}
		
		int[] cntArr = Db.batch("delete from sys_role where role_id=? ", paras, 100);
		
		int cntOk = 0;
		for(int i=0; i<cntArr.length; i++) {
			cntOk = cntOk + cntArr[i];
		}
		
		if(cntArr.length>0) {
			return RetKit.ok("成功删除 "+cntOk+" 条数据");
		}
		
		return RetKit.fail("批量删除失败");
	}
	
	/**
	 * 分配权限
	 * @param roleId
	 * @return
	 */
	public RetKit assignMenu(String roleId) {
        List<SysMenu> menus = menuDao.findAll();
        List<SysRoleMenu> roleMenus = roleMenuDao.find("select * from sys_role_menu where role_id=? ", roleId);
        for (SysMenu menu : menus) {
            menu.setOpen(true);
            menu.setChecked(false);
            for (SysRoleMenu roleMenu : roleMenus) {
                if (menu.getMenuId().equals(roleMenu.getMenuId())) {
                    menu.setChecked(true);
                    break;
                }
            }
        }
        return RetKit.ok().setData(JSONObject.toJSON(menus));
	}
	
	/**
	 * 保存权限分配
	 */
	public RetKit saveMenu(Integer roleId, JSONArray menuIds) {
        int cnt = Db.delete("delete from sys_role_menu where role_id=? ", roleId);
        if (menuIds.size() > 0) {
            List<Record> roleMenuList = new ArrayList<>();
            for (Object menuId : menuIds) {
                Record roleMenu = new Record();
                roleMenu.set("role_id", roleId);
                roleMenu.set("menu_id", menuId);
                
                roleMenuList.add(roleMenu);
            }
            
            int[] cntArr = Db.batchSave("sys_role_menu", roleMenuList, 100);
            
            int cntOk = 0;
    		for(int i=0; i<cntArr.length; i++) {
    			cntOk = cntOk + cntArr[i];
    		}
    		
    		cntOk = Math.abs(cnt - cntOk);
    		
    		return RetKit.ok("保存成功"+cntOk+"条数据");
        }
        
        return RetKit.fail("保存失败");
	}

	
}
